﻿#include "PropTip.h"
#include "PropTipManager.h"
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;
PropTip::PropTip(PropType type):
	type(type),
	loadingCount(0),
	onPropTipBegan(nullptr),
	onPropTipEnded(nullptr)
{

}

PropTip* PropTip::create(PropType type) {
	PropTip* ret = new (std::nothrow) PropTip(type);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

bool PropTip::init() {
	if (!Widget::init()) {
		return false;
	}
	size = Director::getInstance()->getVisibleSize();
	initSpriteFrameCache();
	initCSBFile();
	//scheduleUpdate();
	schedule(schedule_selector(PropTip::loadingUpdate), 0.05, -1, 0);
	return true;
}

/*
	加载csb文件
*/
void PropTip::initCSBFile() {
	root = CSLoader::createNode("scenes/game/ui/prop_tip.csb");
	this->addChild(root);
	prop_tip = dynamic_cast<Sprite*>(root->getChildByName("prop_tip"));
	propTipsize = prop_tip->getContentSize() * 0.5;
	char filename[30];
	sprintf_s(filename, "props_%d.png", type);
	prop_tip->setSpriteFrame(gameSpriteCache->getSpriteFrameByName(filename));

	for (size_t i = 0; i < 3; i++) {
		char filename[20];
		sprintf_s(filename, "LoadingBar_%d", i + 1);
		LoadingBar* loading = dynamic_cast<LoadingBar*>(root->getChildByName(filename));
		loadingVec.push_back(loading);
	}
}

/*
	加载精灵帧缓存
*/
void PropTip::initSpriteFrameCache() {
	gameSpriteCache = SpriteFrameCache::getInstance();
	gameSpriteCache->addSpriteFramesWithFile("scenes/game/image/prop/props_ani.plist",
		Director::getInstance()->getTextureCache()->addImage(
			"scenes/game/image/prop/props_ani.png"));		//向帧缓冲中添加纹理图片
}

/*
	进度条自动递减调度器
*/
void PropTip::loadingUpdate(float dt) {
	loadingCount++;
	if (loadingVec[0]->getPercent() > 0) {
		//auto test = loadingVec[i]->getPercent();
		loadingVec[0]->setPercent(loadingVec[0]->getPercent() - 1);
	} else if (loadingVec[1]->getPercent() > 0) {
		loadingVec[1]->setPercent(loadingVec[1]->getPercent() - 1);
	} else if (loadingVec[2]->getPercent() > 0) {
		loadingVec[2]->setPercent(loadingVec[2]->getPercent() - 1);
	}
	if (onPropTipBegan != nullptr) {
		//道具生效
		onPropTipBegan(true);
	}
	if (loadingCount == 300) {
		if (onPropTipEnded != nullptr) {
			//道具失效
			onPropTipEnded(false);
		}
		unschedule(schedule_selector(PropTip::loadingUpdate));
		PropTipManager::getInstance()->collection(this);
	}
}

/*
	重置
*/
void PropTip::reset() {
	for (size_t i = 0; i < 3; i++) {
		loadingVec[i]->setPercent(100);
	}
	loadingCount = 0;
}
